<script setup>
import { ref } from "vue";
import { postClassAdd, putClassEdit } from "@/api/type";
// 开关
const dialogVisible = ref(false);

// 获取表单dom对象
const form = ref(null);

const emit = defineEmits(["success"]);
const open = async (row) => {
  dialogVisible.value = true;
  //console.log(row)
  formModel.value = { ...row };
};

// 暴露给父组件
defineExpose({
  open,
});

// 表单数据
const formModel = ref({
  className: "",
  classAlias: "",
});
//表单验证规则
const rules = {
  className: [
    { required: true, message: "请输入分类名称", trigger: "blur" },
    {
      pattern: /^\S{1,10}$/,
      message: "分类名必须是1-10位的非空字符",
      trigger: "blur",
    },
  ],
  classAlias: [
    { required: true, message: "请输入分类别名", trigger: "blur" },
    {
      pattern: /^[a-zA-Z0-9]{1,15}$/,
      message: "分类别名必须是1-15位的字母数字",
      trigger: "blur",
    },
  ],
};

// 添加或编辑文章分类
const articleChannel = async () => {
  // 表单预校验
  await form.value.validate();

  // 添加文章分类
  if (!formModel.value.id) {
    const res = await postClassAdd(formModel.value);
  } else {
    // 编辑文章分类
    const res = await putClassEdit(formModel.value);
  }
  //关闭弹窗
  dialogVisible.value = false;
  // 提示成功
  ElMessage({
    message: `${formModel.value.id ? "编辑" : "添加"}成功`,
    type: "success",
    plain: true,
  });
  //
  emit("success");
};
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="formModel.id ? '编辑分类' : '添加分类'"
    width="30%"
  >
    <!-- 内容 -->
    <div>
      <el-form
        ref="form"
        :model="formModel"
        :rules="rules"
        label-width="100px"
        style="padding-right: 30px"
      >
        <el-form-item label="分类名称" prop="className">
          <el-input v-model="formModel.className" minlength="1" maxlength="10">
          </el-input>
        </el-form-item>
        <el-form-item label="分类别名" prop=" classAlias">
          <el-input v-model="formModel.classAlias" minlength="1" maxlength="15">
          </el-input>
        </el-form-item>
      </el-form>
    </div>
    <!-- 按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="articleChannel"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>
</template>
